<?php

class InvoiceLedgerController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($invoice)
    {
        /*
          $jsonData = json_decode($_REQUEST['data'], true);
          foreach ($jsonData as $item) {
          $model = new InvoiceLedger;
          $model->attributes = $item;
          $model->description = $item['description'];
          $model->invoice = $_GET['invoice'];
          $inventotyModel = Inventory::model()->find('partno=:partno', array(
          'partno' => $model->partno));
          $subcat = Invsubcategories::model()->find('subcategory=:subcat', array(
          'subcat' => $inventotyModel->subcat));
          if ($subcat->applymarkup == 'Average Cost')
          $model->cost =  $inventotyModel->averagecost;
          else
          $model->cost =   $inventotyModel->baseprice;
          $model->scredit = $inventotyModel->salescredit;
          $model->sdebit = $inventotyModel->salesdebit;
          $model->cdebit = $inventotyModel->costcredit;
          $model->ccredit = $inventotyModel->costdebit;
          $model->status=1;
          if ($model->save())
          echo 'itemAdded';
          }
         */
        $model = new InvoiceLedger;
        $model->invoice = $invoice;
        $model->noprint = 0;
        $model->taxed = 0;
        $model->status = 2;
        if ($model->save())
        {
            echo "save successfull";
        }
    }

    public function actionSaveBatch() {
        if (isset($_POST['invoice']) && isset($_POST['data'])) {

            $invoice = $_POST['invoice'];
            $data = $_POST['data'];

            $invoiceModel = Invoice::model()->findByPk($invoice);

            if ($invoiceModel != NULL) {


                //$data=json_decode($_POST['data']);
                //echo json_encode($data);
                foreach ($data as $item) {

                    if (isset($item[0]) && $item[0] == 'delete') {
                        if ($item[1] == 'discount') {
                                $invoiceModel->discounted = 0;
                                $invoiceModel->discount_percent = 0;
                                $invoiceModel->discount_memo = 0;
                                $invoiceModel->discount_amount = 0;
                                $invoiceModel->discount_tax = 0;
                                $invoiceModel->discount_total = 0;
                                 if ($invoiceModel->save() === false) {
                                    echo "Removing discount datafailed: " . json_encode($model->getErrors());
                                }
                        } else {
                            $num = Yii::app()->db->createCommand()->delete('tbl_invoice_ledger', 'invoice=:invoice AND id=:id', array(
                                'invoice' => $_POST['invoice'],
                                'id' => $item[1]
                                    ));
                            if ($num == 0)
                                echo "Delete failed at {$item[1]}";
                        }
                    }else {

                        if (isset($item['id']) && $item['id'] != 0) {

                            $model = InvoiceLedger::model()->findByPk(intval($item['id']));

                            $model->warehouse = $item['warehouse'];
                            $model->partno = $item['partno'];
                            $model->description = $item['description'];
                           $model->old_qty=$model->qty;
                            $model->qty = $item['qty'];
                            $model->price = $item['price'];
                            $model->taxed = $item['taxed'];
                            $model->noprint = $item['noprint'];
                            $model->cost = $item['cost'];
                            $model->markupvalue = $item['markupvalue'];

                            if ($model->save() === false) {
                                echo "Update failed: " . json_encode($model->getErrors());
                            }
                        } else {
                            if ($item['partno'] != 'discount') {
                                $model = new InvoiceLedger;
                                //$model->attributes=$item;
                                $model->invoice = $invoice;
                                $model->warehouse = $item['warehouse'];
                                $model->partno = $item['partno'];
                                $model->description = $item['description'];
                                $model->qty = $item['qty'];
                                $model->price = $item['price'];
                                $model->taxed = $item['taxed'];
                                $model->noprint = $item['noprint'];
                                $model->cost = $item['cost'];
                                $model->markupvalue = $item['markupvalue'];
                                if ($model->save() === false) {
                                    echo "Create failed: " . json_encode($model->getErrors());
                                }
                            } else {
                                /*
                                 * @var $invoiceModel Invoice
                                 */
                                $invoiceModel->discounted = 1;
                                $invoiceModel->discount_percent = $item['price'];
                                $invoiceModel->discount_memo = $item['description'];
                                $invoiceModel->discount_amount = $item['tax2'];
                                $invoiceModel->discount_tax = $item['tax1'];
                                $invoiceModel->discount_total = $invoiceModel->discount_amount + $invoiceModel->discount_tax;
                                if ($invoiceModel->save() === false) {
                                    echo "Create discount datafailed: " . json_encode($model->getErrors());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id=NULL)
    {
        if ($id != 0)
        {
            $model = $this->loadModel($id);

            $model->attributes = $_REQUEST;
            if ($model->status == 2)
            {
                $model->status = 1;
            }
            if (isset($_REQUEST['description']))
                $model->description = $_REQUEST['description'];

            if ($model->save())
                echo 'Update succes';
        }elseif ($id == 0)
        {
            $model = new InvoiceLedger;
            $model->attributes = $_REQUEST;
            $model->id = NULL;
            $model->status = 1;
            if ($model->save())
            {
                echo 'Add successful';
            }
            else
            {
                echo json_encode($model->getErrors());
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {

        $model = $this->loadModel($id);
        $model->status = 2;
        $model->save();
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('InvoiceLedger');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = InvoiceLedger::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    //TODO move this code to model
    public function actionGetInvoiceItems($invoice, $page=0, $sort=NULL)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $items = new CActiveDataProvider('InvoiceLedger', array(
                    'criteria' => array(
                        'condition' => "invoice=:invoice AND status!=2",
                        'params' => array(
                            'invoice' => $invoice
                        ),
                        'order' => isset($sort) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL,
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $itemsList = array();
        if ($items->getTotalItemCount() > 0)
        {
            $itemsList['totalCount'] = $items->getTotalItemCount();
            $itemsList['type'] = 'Items';
            foreach ($items->getData() as $i => $item)
            {
                $itemsList['data'][$i] = $item->getAttributes();
                $itemsList['data'][$i]['noprinttext'] = $item->getYesNoValue($item->noprint);
                $itemsList['data'][$i]['taxedtext'] = $item->getYesNoValue($item->taxed);
            }
            echo json_encode($itemsList);
        }
        Yii::app()->end();
    }

    public function actionGetItemsCost()
    {
        $totalCost = 0;
        $jsonData = json_decode($_REQUEST['data'], true);

        foreach ($jsonData as $item)
        {
            $model = Inventory::model()->find('partno=:partno', array(
                'partno' => $item['partno']));

            // echo $model->description;
            if ($model != NULL)
            {

                $totalCost+=$model->getCost() * $item['qty'];
            }
        }

        echo number_format($totalCost, 2, '.', '');
    }

    public function actionGetItemPrice($partno, $pricecode)
    {
        $item = Inventory::model()->findByPk($partno);
        /* @var $item Inventory */
        if ($item != NULL)
        {
            echo $item->getPrice($pricecode);
        }
    }

    public function actionIsItemTaxable($partno, $custno=null,$zipcode=null,$state = null)
    {

        $item = Inventory::model()->findByPk($partno);
        /* @var $item Inventory */
        if ($item != NULL)
        {
            if($custno!=null){
                $rs = $item->isTaxable($custno);    
            }else{
                $rs = $item->isTaxableByZipcodeAndState($zipcode,$state);
            }
            
            if ($rs)
            {
                echo '0';
            }
            else
            {
                echo '1';
            }
        }
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-ledger-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
